import React, { useState, useEffect } from 'react';
import { LoadingOutlined, SaveOutlined } from '@ant-design/icons';
import {
  openNotification_util, fetchsync_util,
  resultdata_to_formdata, addkey_for_mxdata,
  convertISODateTimeToYYYYMMDDHHMMSS,
  view_item_util,
} from '../util/util.js'
import Customfielditem_hook from '../newmes/customfielditem_hook.js'
import moment from 'moment'
import 'moment/locale/zh-cn'
import Xm_zbmx_hook from './xm_zbmx_hook.js';
import { use_gyszb_initformdata_view, use_xm_zbmx_column_initformdata,
   use_zbfp_view_column_initformdata, use_zbfp_column_initformdata } from './use_zbzx_config.js';
moment.locale('zh-cn')
var storage = window.localStorage;
import useStore from '../../useStore.js'
import { Button, Tabs } from 'antd';


const Zbfp_form = () => {
  //动态数据源
  const [dynDatasObject, setdynDatasObject] = useState({
    dict_zbxs: [], query_gys: [], query_ry: [], dict_jjgz: []
  })
  const [isloading, setisloading] = useState(true)

  const [zbmxdata, setzbmxdata] = useState([])
  const [zbmxcolums, setzbmxcolums] = useState(use_zbfp_column_initformdata)
  const [zbmxdelidarr, setzbmxdelidarr] = useState([])
  const [wlmxdata, setwlmxdata] = useState([])
  const [ifzz, setifzz] = useState(true)
  const [activeKey, setactiveKey] = useState(1)
  /**
   * 强制刷新明细表 用于特殊场景
   */
  const [switche, setswitche] = useState(true);
  const forceupdate = () => { setswitche(false) }
  useEffect(() => { switche ? "1" : setswitche(true) }, [switche])



  //主表数据
  const [formdata, setformdata] = useState(use_gyszb_initformdata_view)
  const { collapsed } = useStore();



  //加载主表数据
  const loadformdata = async (data) => {
    let rtdata = await fetchsync_util("/admin/zbzx/query_zbfp_byid", 'POST', { data }, "json")
    if (!rtdata.rtstatus) {
      openNotification_util("该项目不存在")
      return
    }
    rtdata.resultdata.formdata.create_time = rtdata.resultdata.formdata.create_time ? convertISODateTimeToYYYYMMDDHHMMSS(rtdata.resultdata.formdata.create_time) : ""
    rtdata.resultdata.formdata.update_time = rtdata.resultdata.formdata.update_time ? convertISODateTimeToYYYYMMDDHHMMSS(rtdata.resultdata.formdata.update_time) : ""
    rtdata.resultdata.formdata.sqsj = rtdata.resultdata.formdata.sqsj ? convertISODateTimeToYYYYMMDDHHMMSS(rtdata.resultdata.formdata.sqsj) : ""
    rtdata.resultdata.formdata.fbsj = rtdata.resultdata.formdata.fbsj ? convertISODateTimeToYYYYMMDDHHMMSS(rtdata.resultdata.formdata.fbsj) : ""
    rtdata.resultdata.formdata.ybjzsj = rtdata.resultdata.formdata.ybjzsj ? convertISODateTimeToYYYYMMDDHHMMSS(rtdata.resultdata.formdata.ybjzsj) : ""
    rtdata.resultdata.formdata.tbjzsj = rtdata.resultdata.formdata.tbjzsj ? convertISODateTimeToYYYYMMDDHHMMSS(rtdata.resultdata.formdata.tbjzsj) : ""
    rtdata.resultdata.formdata.kbsj = rtdata.resultdata.formdata.kbsj ? convertISODateTimeToYYYYMMDDHHMMSS(rtdata.resultdata.formdata.kbsj) : ""
    // rtdata.resultdata.formdata.gfkj = rtdata.resultdata.formdata.gfkj ? rtdata.resultdata.formdata.gfkj.split(",") : []
    // rtdata.resultdata.formdata.xfkj = rtdata.resultdata.formdata.xfkj ? rtdata.resultdata.formdata.xfkj.split(",") : []
    setformdata({ ...formdata, ...resultdata_to_formdata(rtdata.resultdata.formdata, formdata) });
    setzbmxdata(addkey_for_mxdata(rtdata.resultdata.zzmxdata.sort((a, b) => rtdata.resultdata.formdata.jjgz == '价高优先' ? b.zzbj - a.zzbj : a.zzbj - b.zzbj).map(item => {
      item.dblsdjcz = (item.lsgmdj - item.zzbj).toFixed(2)
      item.hjcz = item.zbsl ? (item.dblsdjcz * item.zbsl).toFixed(2) : 0
      return item
    })))
    setwlmxdata(addkey_for_mxdata(rtdata.resultdata.wlmxdata))
    if (rtdata.resultdata.ifzz) {
      setifzz(true)
      setzbmxcolums(use_zbfp_view_column_initformdata)
    }
    else {
      setifzz(false)
      setzbmxcolums(use_zbfp_column_initformdata)
    }
  }

  const handle_zbsz = async () => {
    var rtdata = await fetchsync_util("/admin/zbzx/save_zbsz", 'POST', { zzmxdata: zbmxdata }, "json")
    openNotification_util(rtdata.rtmessage)
    await loadformdata(JSON.parse(storage.pre_zbfp_item).data)
  }

  // 页面进入加载数据
  useEffect(() => {
    loadformdata(JSON.parse(storage.pre_zbfp_item).data)
    setisloading(false)
  }, [])

  //设置value
  const setfield = (onekey, value, settype) => {
    if (settype == 'single') {
      if (onekey == "zbpl") {
        var newitem = formdata[onekey]
        newitem.value = value.value
        let newformdata = Object.assign({}, formdata, { [onekey]: newitem });
        setformdata(newformdata)
      }
      else {
        var newitem = formdata[onekey]
        newitem.value = value
        let newformdata = Object.assign({}, formdata, { [onekey]: newitem });
        setformdata(newformdata)
      }
    }
    else if (settype == "muti") {
      let [tansferarr, selectrow, newformdata] = [onekey, value, {}];
      tansferarr.forEach(item => {
        var newitem = formdata[item.target]
        newitem.value = selectrow ? selectrow[item.origin] : ""
        newformdata = Object.assign({}, formdata, { [item.target]: newitem });
      })
      setformdata(newformdata)
    }

  }

  const renderfileditem = () => {
    var formdataarr = []
    for (var formitemkey in formdata) {
      formdata[formitemkey].inputType == "none" ? "" : formdataarr.push(formdata[formitemkey])
    }
    var renderstr = formdataarr.map(item => {
      var rtitem = item.input_type == "space_item" ?
        <Customfielditem_hook form={formdata} item={{ inputType: "none" }}
          handlechange={(key, value, settype) => { setfield(key, value, settype) }} />
        :
        <Customfielditem_hook form={formdata} item={formdata[item.dataIndex]}
          dynDatasObject={dynDatasObject}
          handlechange={(key, value, settype) => { setfield(key, value, settype) }} />
      return rtitem
    }
    )
    return renderstr
  }

  return (

    <div style={{
      height: "94%", backgroundColor: `#F1F1F1`, right: "1%", top: "5.9vh", overflow: "hidden",
      backgroundSize: "100% 100%", width: collapsed ? "94%" : "84%", position: "absolute", color: "white", fontSize: "0.8rem"
    }}
    data-page-type="form">

      <div style={{width:"100%",height:"100%",backgroundColor:"white",overflow:"auto"}}>
      <div style={{
        width: "100%", height: "7%", position: "sticky", top: "1%", backgroundColor: "white", color: "black", display: "flex",
        zIndex: 105, borderBottom: "2px solid #a91f24"
      }}>


        <div style={{ width: "40%", textAlign: "left", paddingRight: "1rem", display: "flex", alignItems: "center", fontWeight: "600" }}>
          &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
          工具栏
        </div>
        <div style={{ width: "60%", textAlign: "right", paddingRight: "1rem" }}>
          {/* <Button type="primary" style={styles.button_style} onClick={() => { handle_jjzz() }}>
              <SaveOutlined />竞价终止</Button> */}
          {/* <Button type="primary" style={styles.button_style} onClick={() => { handle_zbsz() }}>
              <SaveOutlined />竞价延时</Button> */}
          {!ifzz && <Button type="primary" style={styles.button_style} onClick={() => { handle_zbsz() }}>
            <SaveOutlined />中标确认</Button>}
        </div>
      </div>

      <div style={styles.kshcontainer}>
        <div style={{
          fontSize: "0.7rem", position: "relative", width: "96%", marginLeft: "2%", backgroundColor: "", display: "flex",
          textIndent: "1rem", justifyContent: "flex-start", alignContent: "flex-start", flexWrap: "wrap", marginBottom: "2rem"
        }}>
          {renderfileditem()}
        </div>
        {/* 主表区域结束 */}
        {/* 中标区域 */}
        <div style={{
          height: "1.2rem", marginLeft: "2%", position: "relative", width: "96%", textIndent: "0.5rem", color: "#666666",
          backgroundColor: "white", lineHeight: "1.2rem", fontSize: "14px", fontWeight: "500", textAlign: "left", borderLeftStyle: "solid",
          borderWidth: "0.3rem", borderColor: "#a91f24", marginTop: "1rem", marginBottom: "0.5rem", letterSpacing: "0.05rem"
        }}>
          中标明细
        </div>
        <div style={{
          fontSize: "0.7rem", position: "relative", width: "96%", marginLeft: "2%", backgroundColor: "", display: "flex",
          textIndent: "1rem", justifyContent: "flex-start", alignContent: "flex-start", flexWrap: "wrap"
        }}>
          {isloading ?
            (<div style={{ width: "10%", height: "10%", position: "absolute", left: "50%", top: "49%", color: "#14d9cc" }}>            <LoadingOutlined /></div>)
            :
            <div style={{ position: "relative", width: "100%", overflowX: "auto", marginBottom: "1rem" }}>

              {wlmxdata.length > 0 && (
                <Tabs defaultActiveKey={activeKey} onChange={(key) => { setactiveKey(key) }} className='task-tabs' >
                  {Array.from({ length: wlmxdata.length }, (_, i) => (
                    <Tabs.TabPane tab={<span>{wlmxdata[i].wlmc}</span>} key={i + 1}>
                      {switche &&
                        <Xm_zbmx_hook colmuns={zbmxcolums}
                          datasource={addkey_for_mxdata(zbmxdata.filter(item => item.bjwlmxid == wlmxdata[i].id)
                            .map((item, index) => {
                              item.pm = index + 1
                              return item
                            }))}
                          styleobj={{ height: "70%" }}
                          showcz={true}
                          zbmxdata={zbmxdata}
                          dynDatasObject={dynDatasObject}
                          formdata={formdata}
                          handledelid={ids => { ids.length !== 0 ? setzbmxdelidarr([...zbmxdelidarr, ...ids]) : ''; }}
                          handgetmxdata={(tabledata) => {
                            addkey_for_mxdata(tabledata)
                            setzbmxdata(tabledata)
                          }}
                          // ifshowaddbtn={JSON.parse(storage.pre_xm_kb_item).type != "view" && formdata.xmzt.value == "待发布" ? true : false}
                          handlechangeFormdata={(data) => {
                            setformdata(data)
                          }}
                          forceupdate={forceupdate}
                        />}
                    </Tabs.TabPane>
                  ))}
                </Tabs>
              )}
            </div>
          }
        </div>
      </div>
      </div>
    </div>
  )
}


export default Zbfp_form
var styles = {
  maincontainer: {
    height: "100vh", backgroundColor: `white`,
    backgroundSize: "100% 100%", width: "100%", position: "absolute", left: "0", color: "white", fontSize: "0.8rem"
  },
  topcontainer: {
    width: "100%", height: "10vw", backgroundImage: "linear-gradient(to bottom,#e4e5eb , white)", paddingTop: "3vw",
    position: "relative", fontSize: "0.89rem", textIndent: "2rem", fontWeight: "800", color: "#a91f24", borderRadius: "0 0 15px 15px"
  },
  butdcstyle: { paddingLeft: "1vw", paddingRight: "1vw", height: "2vw", position: "absolute", right: "1%", top: "0%", backgroundColor: "#a91f24", fontSize: "0.8vw", borderRadius: "0.4rem", borderRadius: "0 0 0.3vw 0.3vw" },
  butmainstyle: { paddingLeft: "1vw", height: "2vw", position: "absolute", right: "6.5%", top: "0%", backgroundColor: "#a91f24", fontSize: "0.8vw", borderRadius: "0.4rem", borderRadius: "0 0 0.3vw 0.3vw" },
  butbackstyle: { borderRadius: "0.4rem", backgroundColor: "#a91f24", height: "2vw", position: "absolute", right: "12%", top: "0%", fontSize: "0.8vw", borderRadius: "0 0 0.3vw 0.3vw" },
  kshcontainer: {
    width: "98%", position: "relative", backgroundColor: "white", color: "#666",
    borderRadius: "10px", paddingBottom: "2rem", overflow: "visible"
  },
}